package com.tabbar.demo.wiget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import com.tabbar.demo.R;

public class SinView extends View {

    private Paint mPaint = null;
    private Path path;
    private float amplitude = 100.0f;//振幅
    private float frequency = 5.0f;    //2Hz
    private float phase = 45.0f;         //相位
    private int height = 0;
    private int margin = 20;//上下间距
    private float waveHeightSmallValue = 80.0f;//上下间距

    private int width = 0;
    private int i = 0;
    private static float px = -1, py = -1;

    private boolean sp = false;
    private int backColor = Color.WHITE;//背景色
    private int lineColor = Color.GREEN;//线的颜色
    private int bgColor = Color.parseColor("#6fc1c1c1");//线的颜色
    private ValueAnimator valueAnimator;
    private boolean isStartAnim = false;

    public SinView(Context context) {
        this(context, null);
    }

//如果不写下面的构造函数，则会报错：custom view SineWave is not using the 2- or 3-argument View constructors

    SinView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SinView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = context.obtainStyledAttributes(attrs,
                R.styleable.SinView);
        amplitude = ta.getDimension(R.styleable.SinView_amplitude, 100);
        frequency = ta.getFloat(R.styleable.SinView_frequency, 10);
        lineColor = ta.getColor(R.styleable.SinView_lineColor, Color.WHITE);
        backColor = ta.getColor(R.styleable.SinView_backColor, Color.BLACK);
        ta.recycle();
        initPaint();
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(bgColor);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(5);
        path = new Path();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        height = this.getHeight();
        width = this.getWidth();
        amplitude = height / 2 - 20;
    }

    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(backColor);
        mPaint.setColor(bgColor);
        canvas.drawLine(0, height / 2, width, height / 2, mPaint);
        if (this.isStartAnim) {
            drawBgWave(canvas);
            drawWave(canvas);
        }
    }

    /**
     * 画背景波形图
     *
     * @param canvas
     */
    private void drawBgWave(Canvas canvas) {
        amplitude = 40;
        mPaint.setColor(bgColor);
        float cy = height / 2;
        for (i = 0; i < width - 1; i++) {
            canvas.drawLine((float) i, cy - amplitude * (float) (Math.sin(phase * 2 * (float) Math.PI / 360.0f + 2 * Math.PI * frequency * i / width)), (float) (i + 1), cy - amplitude * (float) (Math.sin(phase * 2 * (float) Math.PI / 360.0f + 2 * Math.PI * frequency * (i + 1) / width)), mPaint);
        }
    }

    /**
     * 画主波形图
     *
     * @param canvas
     */
    private void drawWave(Canvas canvas) {
        amplitude = height / 2 - margin;
        mPaint.setColor(lineColor);
        float cy = height / 2;
        int tempWaveHeight = height / 2 - 20;
        int part = 24;//分断显示波形
        //波形变化的幅度
        int stepWidth = width / part;//每个波形变化期的宽度4
        float step = (tempWaveHeight - waveHeightSmallValue) / stepWidth;
        int count = 0;
        for (i = 0; i < part; i++) {
            for (int j = 0; j < stepWidth * (i + 1); j++) {
                if (i % 2 == 0) {
                    if (amplitude >= tempWaveHeight) {
                        amplitude = tempWaveHeight;
                        amplitude += step;
                    } else {
                        amplitude += step;
                    }
                } else {
                    if (amplitude <= waveHeightSmallValue) {
                        amplitude = waveHeightSmallValue;
                        amplitude -= step;
                    } else {
                        amplitude -= step;
                    }
                }
                canvas.drawLine((float) count, cy - amplitude * (float) (Math.sin(phase * 2 * (float) Math.PI / 360.0f + 2 * Math.PI * frequency * count / width)), (float) (count + 1), cy - amplitude * (float) (Math.sin(phase * 2 * (float) Math.PI / 360.0f + 2 * Math.PI * frequency * (count + 1) / width)), mPaint);
                count++;
            }
        }
    }


    public void waveAnim() {
        if (valueAnimator == null) {
            valueAnimator = ValueAnimator.ofFloat(0F, 1.0F);
            valueAnimator.setDuration(800);//控制移动快慢，值越小越快
            valueAnimator.setRepeatMode(ValueAnimator.RESTART);//重新启动
            valueAnimator.setRepeatCount(ValueAnimator.INFINITE);//无限重复
            valueAnimator.setInterpolator(new LinearInterpolator());//速率变化
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    Float aFloat = Float.valueOf(animation.getAnimatedValue().toString());
                    phase = 360.F * aFloat;
                    invalidate();
                }
            });
        }
        valueAnimator.start();
    }

    /**
     * 开启动画
     */
    public void startAnim() {
        this.isStartAnim = true;
        if (valueAnimator==null||!valueAnimator.isRunning())
            waveAnim();
    }

    /**
     * 结束动画
     */
    public void stopAnim() {
        this.isStartAnim = false;
        if (valueAnimator != null && valueAnimator.isRunning()) {
            valueAnimator.cancel();
        }
    }
}